package com.hup.utils.swing.customView.viewTable2;

import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.util.List;

/**
 * 数据行的[右键菜单]
 */
public abstract class VRowMenu<R> implements ActionListener {
    private final JPopupMenu rowMenu;

    public VRowMenu() {
        this.rowMenu = new JPopupMenu();
        for (JMenuItem item : buildMenu()) {
            if (item == null) {
                rowMenu.addSeparator();
                continue;
            }
            rowMenu.add(item);
            item.addActionListener(this);
        }
    }

    public void mouseClicked(ViewTable<R> table, MouseEvent e) {
        int row = table.rowAtPoint(e.getPoint());
        //log.info("row={}", row);
        if (row == -1) return;//不会发生...

        if (selectOneRow()) {
            table.setRowSelectionInterval(row, row);
        } else {
            /*
            处理菜单选中,参考windows:
            1.当前行没选中,选中当前行,并弹出菜单
            2.当前行选中,直接弹出菜单
            */
            boolean isSelected = table.getSelectionModel().isSelectedIndex(row);
            if (!isSelected) {
                if (e.isControlDown() || e.isShiftDown()) {
                    table.addRowSelectionInterval(row, row);
                } else {
                    table.setRowSelectionInterval(row, row);
                }
            }
        }

        boolean showMenu = beforeShowMenu(rowMenu, table,
                table.getSelectedRowCount(),
                table.convertRowIndexToModel(row));
        if (showMenu) rowMenu.show(table, e.getX(), e.getY());
    }

    //===可重写的方法

    /**
     * null元素,代表[分割线]
     *
     * @return 菜单
     */
    public abstract List<JMenuItem> buildMenu();

    @Override
    public abstract void actionPerformed(ActionEvent e);

    /**
     * 用途:
     * .控制菜单显示
     * .动态更新菜单内容
     *
     * @param row modelIndex
     * @return false-本次事件不弹出菜单
     */
    public boolean beforeShowMenu(JPopupMenu rowMenu, ViewTable<R> table, int selectedRowCount, int row) {
        return true;
    }

    /**
     * @return true-弹出菜单时, 只能选中一行
     */
    public boolean selectOneRow() {
        return false;
    }

}
